#! /usr/bin/env python
# -*- coding: utf-8 -*-
# __author__ = "Q1mi"
# Date: 2018/10/29

import numpy as np
import math
#################一元一次################

def linefit(x , y):
    N = float(len(x))
    sx,sy,sxx,syy,sxy=0,0,0,0,0
    for i in range(0,int(N)):
        sx  += x[i]
        sy  += y[i]
        sxx += x[i]*x[i]
        syy += y[i]*y[i]
        sxy += x[i]*y[i]
    a = (sy*sx/N -sxy)/( sx*sx/N -sxx)
    b = (sy - a*sx)/N
    r = abs(sy*sx/N-sxy)/math.sqrt((sxx-sx*sx/N)*(syy-sy*sy/N))
    return a,b,r


###################一元二次####################
def f(x):
    return x ** 2 + 1


def f_fit(x, y_fit):
    x = np.array(x)
    a, b, c = y_fit.tolist()
    return a * x ** 2 + b * x + c

############7,15,40区分表达##############################
class Rule(object):
    def __init__(self,day,original_data):
        self.day = day
        self.original_data = original_data
        self.text = ''
        self.wd_max = self.original_data['wd_max'].astype(int)
        self.wd_min = self.original_data['wd_min'].astype(int)

    def rain(self):
        ##判断是否有雨，获取有雨的日期
        wat = self.original_data['weater'].tolist()
        rain_time = []
        weater_lise = []

        for indexs in self.original_data.index:
            weater =  self.original_data.ix[indexs,'weater']
            if '雨' in weater :
                rain_time_pre = self.original_data.ix[indexs,'time']
                weater_lise.append('雨')
                rain_time.append(rain_time_pre)
            else:
                weater_lise.append(weater)
        self.original_data['weater'] = weater_lise
        return rain_time

    def weater_cut(self):
        ##日均温差
        self.original_data['wd_cut']= self.original_data['wd_max']- self.original_data['wd_min']
        self.original_data['wd_cut_gz'] = self.original_data.wd_cut.apply(lambda x: 1 if x >= 7 else 0)
        ##日期保存
        cut_weater_time = self.original_data[self.original_data['wd_cut_gz'] == 1]['YBTM'].apply(
            lambda x: x.strftime("%m-%d:")).tolist()  # %Y-%m-%d

        return cut_weater_time

    def weater_comparison(self):
        ##跟前一天的温度对比
        self.original_data['flu_max'] = self.original_data['wd_max'] - self.original_data['wd_max_1']
        self.original_data['flu_min'] = self.original_data['wd_min'] - self.original_data['wd_min_1']

        ##最高温--白天的温度对比
        self.original_data['original_low'] = self.original_data.flu_max.apply(lambda x: 1 if x <= -3 else 0)
        self.original_data['original_up'] = self.original_data.flu_max.apply(lambda x: 1 if x >= 3  else 0)

        ##最高温--白天的温度对比
        self.original_data['original_low_night'] = self.original_data.flu_min.apply(lambda x: 1 if x <= -3 else 0)
        self.original_data['original_up_night'] = self.original_data.flu_min.apply(lambda x: 1 if x >= 3 else 0)
        return self.original_data

    def specical_weater(self):
        ###特殊天气
        ts_weater = ['暴雨', '雷阵雨', '大雨', '雪']
        ts_time =[]
        ts_name = []
        for indexs in self.original_data.index:
            weater =  self.original_data.ix[indexs,'weater']
            for ts in ts_weater:
                if ts in weater:
                    ts_time_pre = self.original_data.ix[indexs,'time']
                    ts_name.append(ts)
                    ts_time.append(ts_time_pre)
        return ts_name,ts_time


    def Slope(self):
        ##一元一次方程
        a_max, b1, r1 = linefit(range(len(self.original_data)), self.original_data['wd_max'].tolist())
        #test_y_max = [a_max * x + b1 for x in range(len(weater_flu))]

        #####二元一次方程
        # x = list(range(len(self.original_data)))
        # y = self.original_data['wd_max'].tolist()
        # y_fit = np.polyfit(x, y, 2)  # 二次多项式拟合
        # y_show = np.poly1d(y_fit)  # 函数优美的形式
        # a, b, c = y_fit.tolist()
        return a_max

class Expression(Rule):
    #super(B,self).__init__()

    def public(self):
        ##公用的表达
        ts_name, ts_time = self.specical_weater()
        self.text = '未来{}天'.format(self.day)

        #特殊天气
        if ts_time:
            for x in list(zip(ts_name,ts_time)):
                self.text += ',{},将有{} \n'.format(x[1],x[0])


    def weater_process(self):
        # 目的地出发过程的天气
        # 未来15天温度持续降低，白天降至11℃，夜间降至1℃，请多带御寒衣物。
        ##未来趋势
        x = range(len(self.original_data))
        a_max, b1, r1 = linefit(x, self.original_data['wd_max'].astype(int).tolist())
        a_min, b2, r2 = linefit(x, self.original_data['wd_min'].astype(int).tolist())

        wd_max = self.original_data['wd_max'].astype(int)
        wd_min = self.original_data['wd_min'].astype(int)
        ##白天上升趋势
        if  a_max >= 0.1:
            if a_min <= -0.1:
                self.text += '白天气温呈上升趋势，白天升至{}℃，昼夜温差较大，夜间最低温{}℃'.format( self.wd_max.max(), self.wd_min.min())
            else:
                self.text += '整体呈上升趋势，白天升至{}℃，夜间升至{}℃'.format( self.wd_max.max(), self.wd_min.max())
        ##白天下降趋势
        elif  a_max <= -0.1:

            if a_min >= 0.1:
                self.text += '白天气温呈下降趋势，白天降至{}℃，夜间回温，从{}℃升至{}℃'.format( self.wd_max.min(), self.wd_min.min(),
                                                                        self.wd_min.max())
            else:
                self.text += '未来{}天整体呈下降趋势，白天降至{}℃，夜间降至{}℃'.format(self.wd_max.min(), wself.d_min.min())
        else:

            weater_comparison_data = self.weater_comparison()
            ##温度幅度是否很大
            original_low = weater_comparison_data[weater_comparison_data['original_low'] == 1]
            low_time = original_low['YBTM'].tolist()

            if len(low_time) >=1:
                self.text += '{}起大幅降温,降至{}℃,夜间气温在{}~{}℃波动'.format(self.low_time[0],self.wd_max.min(),self.wd_min.min(),self.wd_min.max())
            else:
                if a_min <= -0.1:
                    self.text += '夜间整体呈下降趋势,夜间降至{}℃,白天气温在{}~{}℃波动'.format(self.wd_min.min(),self.wd_max.min(),self.wd_max.max())
                elif a_min >= 0.1:
                    self.text += '夜间整体呈上升趋势,夜间从{}℃升至{}℃,白天气温在{}~{}℃波动'.format( self.wd_min.min(),wd_min.max(),self.wd_max.min(), self.wd_max.max())
                ##如果上面的都没有实现
                else:
                    self.text += '温度整体变幅不大,白天平均温度{}℃，夜间平均温度{}℃'.format(round(self.wd_max.mean()),round(self.wd_min.mean()))


    def simple_day(self):
        self.public()
        original_data = self.weater_comparison()
        ##下雨日期
        rain = self.rain()

        ##温度幅度是否很大
        original_low = original_data[original_data['original_low'] == 1]
        low_time = original_low['time'].tolist()
        original_up = original_data[original_data['original_up'] == 1]
        up_time = original_up['time'].tolist()
        main_weater = self.original_data['weater'].value_counts().index[0]

        if self.day == 7:
            ##是否下雨，具体到天
            if len(rain) > 0:
                if '雨' not in self.text:
                    self.text += '有雨 \n'
            else:
                self.text += '{}\n'.format(main_weater) #主要天气

            ##温度幅度是否很大
            ##白天的变化幅度
            if len(original_low) > 0:
                text_low = '{},白天有大幅降温，从{}℃降至{}℃ \n'.format(','.join(low_time),
                                                              original_low['wd_max_1'].tolist()[0],
                                                              original_low['wd_max'].tolist()[0])

            if len(original_low) > 0 or len(original_up) > 0:
                # self.text += '气温波动较大 \n'
                if len(original_up) > 0:
                    if len(original_low) and original_low['YBTM_1'].min() < original_up['YBTM_1'].min():
                        self.text += text_low
                        self.text += '{}回温\n'.format(up_time[0])
                        self.text += '全天气温{}~{}℃\n'.format(
                            self.original_data[self.original_data['time'] == up_time[0]]['wd_min'].tolist()[0],
                            self.original_data[self.original_data['time'] == up_time[0]]['wd_max'].tolist()[0])


                    else:
                        text_up = '{}白天有大幅升温,从{}升至{}℃\n'.format(up_time[0],
                                                                 original_up['wd_max_1'].tolist()[0],
                                                                 original_up['wd_max'].tolist()[0])


                        if len(original_low) > 0:
                            self.text += text_up
                            self.text += text_low

                        else:
                            self.text += text_up
                            self.text += '夜间气温在{}~{}℃波动\n'.format(self.wd_min.min(), self.wd_max.max())

            # if len(low_time) > 0:
            #     self.text += '{},白天有大幅降温，从{}℃降至{}℃ \n'.format(','.join(low_time),original_low['wd_max_1'].tolist()[0], original_low['wd_max'].tolist()[0] )
            #
            # if len(up_time) > 0:
            #     if len(low_time) and original_low['YBTM_1'].min() < original_up['YBTM_1'].min():
            #         text_up = '回温'
            #     else:
            #         text_up = '白天有大幅升温'
            #
            #     self.text += '{}{}，全天气温{}~{}℃\n'.format(','.join(up_time),text_up, original_up['wd_min'].tolist()[0],
            #                                          original_up['wd_max'].tolist()[0])


            ##晚上的变化幅度
            night_data = original_data.loc[(~original_data['original_low'].isin([1])) & (~original_data['original_up'].isin([1]))]

            original_low_night = night_data[night_data['original_low_night'] == 1]
            low_time_night = original_low_night['time'].tolist()
            if len(up_time) == 0:
                if len(low_time_night) > 0:
                    self.text += '{},晚上有大幅降温,全天气温{}~{}℃\n'.format(','.join(low_time_night),original_low_night['wd_min'].tolist()[0] , original_low_night['wd_max'].tolist()[0] )

                original_up_night = night_data[night_data['original_up_night'] == 1]
                up_time_night = original_up_night['time'].tolist()

                if len(up_time_night) > 0:
                    if len(low_time_night) and original_low_night['YBTM_1'].min() < original_up_night['YBTM_1'].min():
                        text_up_night = '回温'
                    else:
                        text_up_night = '晚上有大幅升温'

                    self.text += '{}{},全天气温{}~{}℃\n'.format(','.join(up_time_night),text_up_night,self.wd_min[0] , self.wd_max[0])



        elif self.day == 15:
            self.text += '{}天为主\n'.format(main_weater)  # 主要天气

            ##白天的整体波动
            if len(original_low) > 0:
                text_low = '{}起有{}次大幅降温过程,白天降至{}℃\n'.format(low_time[0], len(original_low),self.wd_max.min())

            if len(original_low)>0 or len(original_up) >0 :
                #self.text += '气温波动较大 \n'
                if len(original_up) > 0:
                    if len(original_low) and original_low['YBTM_1'].min() < original_up['YBTM_1'].min():
                        self.text += text_low
                        self.text  += '{}回温\n'.format(up_time[0])
                    else:
                        self.text += '{}起有{}次大幅升温过程,白天升至{}℃\n'.format(up_time[0], len(up_time),
                                                                           self.wd_max.max())
                        if len(original_low) > 0:
                            self.text += text_low
                else:
                    self.weater_process()
            else:
                self.weater_process()



        else:

            #未来40天，温度持续降低，白天温度15-25度之间，夜间温度保持在13-18度。
            xl = self.Slope()
            if xl <= -0.1:
                self.text += '温度持续降低 \n'
            elif xl >= 0.1:
                self.text += '温度整体呈上升趋势\n'
            else:
                self.text += '气温总体平稳\n'
            if original_data['wd_max'].min() == 0:
                print(original_data[['wd_max','YBTM']])
                print(original_data)
            self.text += '白天温度在{}~{}℃波动\n'.format(original_data['wd_max'].min(),original_data['wd_max'].max())
            self.text += '夜间温度保持在{}~{}℃\n'.format(original_data['wd_min'].min(),original_data['wd_min'].max())

            ######总体统计---xx次降温/升温，xx次降雨

            # if len(rain) > 0 :
            #     text+= '预计会遇到{}个雨天\n'.format(len(rain) )
            # if len(original_low) >0:
            #     text += '{}次大幅降温,发生在'.format(len(original_low),','.join(low_time))
            #     data_day_low = original_low['time'].tolist()
            #     for dt_low in data_day_low:
            #         dt_data_low = original_low[original_low['time'] == dt_low]
            #         text += '{}(气温{}~{}℃)'.format(dt_low, str(max(dt_data_low['wd_min'])), str(max(dt_data_low['wd_max'])))
            #
            #     min_max_weater = original_data[original_data['wd_max'] == original_data['wd_max'].min()]
            #     text += '\n{}白天气温降至近期最低温{}℃ \n'.format(min_max_weater['time'].tolist()[-1],original_data['wd_max'].min())
            #
            # if len(original_up) >0:
            #     text += '{}次大幅升温'.format(len(original_up))
            #
            #     data_day = original_up['time'].tolist()
            #     for dt in data_day:
            #         dt_data = original_up[original_up['time'] == dt]
            #         text += '({}气温{}~{}℃)'.format(dt, str(max(dt_data['wd_min'])), str(max(dt_data['wd_max'])))

